<template>
    <div class="avatar-uploader">
      <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-button size="small" type="primary" @click="uploadAvatar">上传头像</el-button>
    </div>
  </template>
  
  <script>
  export default {
    props: {
      value: {
        type: String,
        default: ''
      },
      uploadUrl: {
        type: String,
        default: '/api/upload/avatar'
      }
    },
    data() {
      return {
        imageUrl: this.value
      }
    },
    watch: {
      value(newVal) {
        this.imageUrl = newVal
      }
    },
    methods: {
      handleAvatarSuccess(res, file) {
        if (res.code === 200) {
          this.imageUrl = res.data.url
          this.$emit('input', this.imageUrl)
          this.$message.success('上传成功')
        } else {
          this.$message.error(res.message || '上传失败')
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
          return false
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
          return false
        }
        return true
      },
      uploadAvatar() {
        this.$refs.upload.submit()
      }
    }
  }
  </script>
  
  <style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  </style>    